package com.mdl.springmvc.handler.handlers;

import com.mdl.springmvc.handler.dao.DepartmentDao;
import com.mdl.springmvc.handler.dao.EmployeeDao;
import com.mdl.springmvc.handler.entity.Employee;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
 * @Desc
 * @Author madengling
 * @Time 2020/11/3 20:07
 */
@Controller
public class EmployeeHandler {
    private static Logger logger = Logger.getLogger(EmployeeHandler.class);
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;
//    ModelAttributeMethodProcessor
//    ConversionService

    @ModelAttribute
    public void getEmployee(@RequestParam(value = "id",required = false)Integer id,
                            Map<String, Object> map){
        if(id != null){
            map.put("employee",employeeDao.get(id));
        }
    }

    @RequestMapping(value = "/delete_emp",method = RequestMethod.POST)
    public String delete(Integer id){
        logger.info("delete_emp");
        employeeDao.delete(id);
        return "redirect:/emps";
    }

    @RequestMapping(value = "/emp",method = RequestMethod.POST)
    public String saveOrUpdate(@Valid Employee employee, BindingResult result,
                               Map<String,Object> map){
        logger.info("emp save");
        if(result.getErrorCount() > 0){
            logger.info("类型转换异常！");
            for(FieldError error : result.getFieldErrors()){
                logger.error(error.getField() + ":" + error.getDefaultMessage());
            }
            //若验证出错，则转向定制的页面
            map.put("departments",departmentDao.getDepartments());
            return "input";
        }
        logger.info(employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @RequestMapping(value = "/emp",method = RequestMethod.GET)
    public String input(Map<String,Object> map,Integer id){
        logger.info("emp input");
        map.put("departments",departmentDao.getDepartments());
        if(id!=null && !StringUtils.isEmpty(id)){
            map.put("employee",employeeDao.get(id));
        }else {
            map.put("employee",new Employee());
        }
        return "input";
    }

    @RequestMapping("/emps")
    public String list(Map<String,Object> map){
        logger.info("emps");
        map.put("employees",employeeDao.getAll());
        return "list";
    }

//    @InitBinder
//    public void initBinder(WebDataBinder binder){
//        binder.setDisallowedFields("lastName");
//    }
}
